#!/bin/bash

set -x

# default to update source then build

TOP_DIR=$(pwd)
SRC_DIR=$TOP_DIR/lib_source
BD_DIR=$TOP_DIR/lib_build
BIN_DIR=$TOP_DIR/lib_bin

export PATH=$TOP_DIR/cross/bin:$PATH

# export MAKE_OPT="-j 2"

cmd=all64
if [ -n "$1" ] ; then
	cmd=$1
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "update" ] ; then
	mkdir -p $SRC_DIR || exit 0
	cd $SRC_DIR
	if [ ! -d ffmpeg ] ; then
		svn co svn://svn.mplayerhq.hu/ffmpeg/trunk ffmpeg
	else
		cd ffmpeg
		svn up
		cd ..
	fi
	cd ..
fi


if [ "$cmd" == "all64" ] || [ "$cmd" == "b64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
	ARCH_FLAG="--arch=x86_64"
	ARCH_PREFIX="x86_64-w64-mingw32-"
	if [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
		ARCH_FLAG="--arch=x86"
		ARCH_PREFIX="i686-w64-mingw32-"
	fi
	rm -rf $BIN_DIR/ffmpeg
	mkdir -p $BD_DIR
	cd $BD_DIR
	rm -rf bd_ffmpeg
	mkdir bd_ffmpeg
	cd bd_ffmpeg
	# patch to remove mingw version test
	patch -d $SRC_DIR/ffmpeg -p0 < $TOP_DIR/patch/ffmpeg-w64.patch
	patch -d $SRC_DIR/ffmpeg/libswscale -p0 < $TOP_DIR/patch/ffmpeg-swscale.patch 
	$SRC_DIR/ffmpeg/configure --prefix=$BIN_DIR/ffmpeg \
		--cross-prefix=$ARCH_PREFIX  \
		--target-os=mingw32 $ARCH_FLAG \
		--enable-memalign-hack --disable-devices \
		--enable-gpl \
		--enable-shared --disable-static

#		--disable-stripping --enable-debug
#	--enable-shared --disable-static \

	make $MAKE_OPT
	make install
	patch -d $SRC_DIR/ffmpeg -p0 -R < $TOP_DIR/patch/ffmpeg-w64.patch
	patch -d $SRC_DIR/ffmpeg/libswscale -p0 -R < $TOP_DIR/patch/ffmpeg-swscale.patch 
	cd ..
	cd ..
fi

date

